﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Common.Lists;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Entities.Users;

namespace BrandonHaynes.Providers.AmazonS3
	{
	/// <summary>
	/// Miscelleaneous extension methods, used to (hopefully) increase readibility.
	/// </summary>
	static class Extensions
		{
		#region DotNetNuke Helper Methods

		/// <summary>
		/// Creates the specified profile property with the given name, if it does not already exist
		/// </summary>
		public static void EnsureProfilePropertyExists(string profilePropertyName, int portalId)
			{
			if (ProfileController.GetPropertyDefinitionByName(portalId, profilePropertyName) == null)
				ProfileController.AddPropertyDefinition(
					new ProfilePropertyDefinition(portalId)
					{
						DataType = new ListController().GetListEntryInfo("DataType", "Text").EntryID,
						Length = 64,
						DefaultValue = string.Empty,
						PropertyCategory = "S3",
						PropertyName = profilePropertyName,
						Visibility = UserVisibilityMode.AdminOnly,
						Visible = true
					});
			}

		/// <summary>
		/// Determines if an HttpContext represents a "direct" file request (a DotNetnuke URI of the form
		/// http://domain.com/path/LinkClick.aspx?fileticket=..., with the fileticket querystring parameter
		/// being the identifying factor.
		/// </summary>
		/// <param name="httpContext">An httpContext to evaluate</param>
		/// <returns>True if the request represents a direct file access; false otherwise (or if the httpContext itself is null)</returns>
		public static bool IsDirectFileRequest(this HttpContext httpContext)
			{ return httpContext != null && httpContext.Request != null && !string.IsNullOrEmpty(httpContext.Request.QueryString["fileticket"]); }

		#endregion

		#region Miscelleaneous Helper Methods

		/// <summary>
		/// Converts a singleton into an enumeration (why isn't this in System.Linq?)
		/// </summary>
		public static IEnumerable<T> ToEnumerable<T>(this T element)
		{ return Enumerable.Repeat(element, 1); }

		/// <summary>
		/// Executes an action against each element in an enumeration (why isn't this in System.Linq?)
		/// </summary>
		public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
			{
			foreach (T t in sequence)
				action(t);
			}

		#endregion
		}
	}
